import GoEasy, { ConnectOptions, ConversationDTO } from 'goeasy';

const goEasy = GoEasy.getInstance({
  host: process.env.VUE_APP_BASE_GO_EASY_HOST, //应用所在的区域地址:
  appkey: process.env.VUE_APP_BASE_GO_EASY_APPKEY, // common key,
  modules: ['im'],
  // true表示支持通知栏提醒，false则表示不需要通知栏提醒
  allowNotification: true //仅有效于app,小程序和H5将会被自动忽略
});

type Message = {
  toType: string;
  senderId: string;
  groupId: string;
};

goEasy.onClickNotification((message: Message) => {
  let currentUrl;
  const routes = getCurrentPages();

  if (routes && routes.length) {
    const curRoute = routes[routes.length - 1].route;
    const curParam = (routes[routes.length - 1] as any).options;
    currentUrl = '/' + curRoute + `?to=${curParam.to}`;
  }

  let newUrl;
  switch (message.toType) {
    case GoEasy.IM_SCENE.PRIVATE:
      newUrl = '/pages/chat/privateChat/privateChat?to=' + message.senderId;
      break;
    case GoEasy.IM_SCENE.GROUP:
      newUrl = '/pages/chat/groupChat/groupChat?to=' + message.groupId;
      break;
  }

  if (currentUrl !== newUrl) {
    uni.navigateTo({
      url: String(newUrl)
    });
  }
});

export function useGoEasy() {
  return goEasy;
}

interface GoEasyUser {
  name: string;
  avatar: string;
}

export interface ConnectGoEasyOptions extends ConnectOptions {
  data: GoEasyUser;
}

export function goEasyIsConnected(goEasy: GoEasy) {
  return goEasy.getConnectionStatus() === 'disconnected';
}

export function useConnectGoEasy(options: ConnectGoEasyOptions) {
  const goEasy = useGoEasy();
  if (!goEasyIsConnected(goEasy)) {
    return Promise.resolve('已连接');
  }
  return new Promise((resolve, reject) => {
    goEasy.connect({
      ...options,
      onSuccess: () => {
        console.log('GoEasy connect successfully.');
        resolve('GoEasy connect successfully.');
        useLoadConversations();
        useGoEasyListen();
      },
      onFailed: (error) => {
        console.log('Failed to connect GoEasy, code:' + error.code + ',error:' + error.content);
        reject(error);
      },
      onProgress: (attempts) => {
        console.log('GoEasy is connecting', attempts);
      }
    });
  });
}

interface GoEasyResponse {
  unreadTotal: number;
  conversations: ConversationDTO[];
}

function renderConversations(content: GoEasyResponse) {
  const { unreadTotal } = content;
  if (unreadTotal > 0) {
    uni.setTabBarBadge({
      index: 3,
      text: unreadTotal.toString()
    });
  } else {
    uni.removeTabBarBadge({
      index: 3
    });
  }
}

export function useLoadConversations() {
  goEasy.im.latestConversations({
    onSuccess: (result) => {
      console.log('加载成功', result);
      renderConversations(result.content);
    },
    onFailed: (error) => {
      console.log('获取最新会话列表失败, error:', error);
    }
  });
}

export function useGoEasyListen() {
  // 会话列表变化
  goEasy.im.on(GoEasy.IM_EVENT.CONVERSATIONS_UPDATED, (content) => {
    renderConversations(content);
  });
}
